package org.lql.algo.codecrush.hot100.linked;

import org.lql.algo.common.ListNode;

/**
 * @author: liangqinglong
 * @date: 2025-09-28 21:41
 * @description: 142. 环形链表 II <a href="https://leetcode.cn/problems/linked-list-cycle-ii/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class DetectCycle {

	public ListNode detectCycle(ListNode head) {
		// 边界判断
		if (head == null || head.next == null) {
			return null;
		}
		ListNode slow = head;
		ListNode fast = head;
		while (fast != null && fast.next != null) {
			slow = slow.next;
			fast = fast.next.next;
			if (slow == fast) {
				slow = head;
				while (slow != fast) {
					fast = fast.next;
					slow = slow.next;
				}
				return slow;
			}
		}
		return null;
	}
}
